const jwt = require('express-jwt');
const ExpressJwt = require('express-jwt');
const JWT = require('jsonwebtoken');
const {TOKEN_KEY} = require('./constans');



/**
 * @description: 解析token
 * @param {*}
 * @return {*}
 */
const jwtAuthor = ExpressJwt((
    {
        //2020.7.7更新后需要指定算法
        algorithms:['HS256'],
        //签名的密钥
        secret:TOKEN_KEY,
        //设置为true表示校验，false表示不校验
        credentialsRequired:true,
        //指定解析结果存放字段，默认为user
        requestProperty:'user',
        //自定义获取token的函数
        getToken:(req)=>{
            if(req.headers.token)return req.headers.token;
        }
    }
)).unless({
    //设置白名单，不进行token校验
    path:['/login']
});



//验证token的有效性
const verifyJWT = (req,res)=>{
    const token = req.get('token');
    JWT.verify(token,TOKEN_KEY,(err,data)=>{
        if(err&&err.name=='TokenExpiredError'){
           return res.json({
               code:500,
               message:"Token失效请重新登录！",
               data:null
           })
        }
        if(err&&err.name=='JsonWebTokenError'){
            return res.json({
                code:500,
                message:err.message,
                data:null
            })
        }
        return data;
    });
}



//解析
const decodeJWT = (req)=>{
    const token = req.get('token');
    return JWT.decode(token);
}




module.exports = {
    jwtAuthor,
    verifyJWT,
    decodeJWT
}